#include <iostream>
using std::cout;
using std::endl;

class Base
{
public:
    virtual void print() const{
        cout << _base << endl;
    }

    long _base = 10;
};


class Derived
: public Base
{
public:
    void display() const{
        cout << _derived << endl;
    }
    long _derived = 100;
};

void test1(){
    Base base;
    Derived d1;

    Base * pbase = &d1;
    /* Base * pbase = &base; */
    //此时将pbase向下转型为Derived*是合理的
    //但是仍然不能直接进行向下转型
    /* Derived * pderived = pbase; */
    
    Derived * pderived = dynamic_cast<Derived*>(pbase);

    if(pderived){
        cout << "转换成功" << endl;
        pderived->display();
    }else{
        cout << "转换失败" << endl;
    }

}


void test0(){
    cout << sizeof(Base) << endl;
    cout << sizeof(Derived) << endl;

    Base base;
    Derived d1;

    //可以用派生类对象给基类对象赋值
    //但是不能用基类对象给派生类对象赋值
    //
    //会调用Base类的赋值运算符函数
    //const Base & rhs = d1;
    base = d1;
    /* d1 = base; */

    //可以用基类指针指向派生类对象
    //不能用派生类指针指向基类对象
    Base * pbase = &d1;
    //pbase只能访问d1对象中基类子对象的部分
    //不能访问Derived类自己定义的部分
    pbase->_base;
    pbase->print();
    /* pbase->_derived; */
    /* pbase->display(); */

    /* Derived * pderived = &base; */

    //可以用基类引用绑定派生类对象
    //不能用派生类引用绑定基类对象
    Base & refb = d1;
    refb._base;
    refb.print();
    /* refb._derived; */
    /* refb.display(); */

    /* Derived & refd = base; */
}


int main(void){
    test1();
    return 0;
}
